/*
 * Copyright (C) 2015 yixun All Rights Reserved.
 *
 * AreaServiceImpl.java
 */
package com.yixun.qfbao.api.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.yixun.qfbao.api.service.ResourcesService;
import com.yixun.qfbao.apidto.*;
import com.yixun.qfbao.model.enums.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.yixun.qfbao.api.service.EstateAdviserService;
import com.yixun.qfbao.api.service.LoginService;
import com.yixun.qfbao.mapper.ResourcesMapper;
import com.yixun.qfbao.mapper.WxBindMapper;
import com.yixun.qfbao.model.Company;
import com.yixun.qfbao.model.CompanyRelation;
import com.yixun.qfbao.model.Dictionary;
import com.yixun.qfbao.model.EstateAdviser;
import com.yixun.qfbao.model.PartnerInfo;
import com.yixun.qfbao.model.PasswordUtil;
import com.yixun.qfbao.model.Resources;
import com.yixun.qfbao.model.WxBind;
import com.yixun.qfbao.model.dto.CompanyDto;
import com.yixun.qfbao.model.dto.CompanyRelationDto;
import com.yixun.qfbao.model.dto.PartnerInfoDto;
import com.yixun.qfbao.model.dto.UserResourcesDto;
import com.yixun.qfbao.model.dto.WxBindDto;
import com.yixun.qfbao.service.CompanyRelationService;
import com.yixun.qfbao.service.CompanyService;
import com.yixun.qfbao.service.DictionaryService;
import com.yixun.qfbao.service.PartnerInfoService;
import com.yixun.qfbao.util.WeixinCommon;
import com.yixun.qfbao.util.WxAccessTokenCacheUtils;
import com.yixun.qfbao.util.WxReqestUtil;
import com.yixun.qfbao.xf.model.Premises;
import com.yixun.qfbao.xf.model.dto.CaseMemberDto;
import com.yixun.qfbao.xf.model.dto.PremisesDto;
import com.yixun.qfbao.xf.model.enums.PremisesStatusEnum;
import com.yixun.qfbao.xf.model.enums.ResultEnum;
import com.yixun.qfbao.xf.service.CaseMemberService;
import com.yixun.qfbao.xf.service.PremisesService;


/**
 * [文件名称]<br>
 * LoginServiceImpl.java<br>
 * <br>
 * [文件描述]<br>
 * 登录、退出相关<br>
 * <br>
 *
 * @author JHSong
 * @version 1.00
 */
@Service
public class LoginServiceImpl implements LoginService {

	@Value("${system.domain}")
	private  String domainName;

    @Autowired
    private CompanyService companyService;
    @Autowired
    private PartnerInfoService partnerInfoService;
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private CompanyRelationService companyRelationService;
    @Autowired
    private PremisesService premisesService;
    @Autowired
    private CaseMemberService caseMemberService;
    @Autowired
    private ResourcesMapper resourcesMapper;
    @Autowired
    private EstateAdviserService estateAdviserService;
    @Autowired
    WxAccessTokenCacheUtils wxAccessTokenCacheUtils;
    @Autowired
    WxReqestUtil wxReqestUtil;
    @Autowired
    WeixinCommon weixinCommon;
    @Autowired
    WxBindMapper wxBindMapper;
    @Autowired
    ResourcesService resourcesService;
    @Override
    public LoginResDto login(LoginReqDto reqDto) {
        LoginResDto loginResDto = new LoginResDto();

        String loginType = reqDto.getLoginType();
        String domain = reqDto.getDomain();
        String companyUuid = reqDto.getCompanyUuid();
        Company company = new Company();

        if (StringUtils.isEmpty(domain) && StringUtils.isEmpty(companyUuid)) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("商户信息获取失败!");
            return loginResDto;
        }

        CompanyDto cDto = new CompanyDto();
        cDto.setDomain(domain);
        cDto.setStatus(CheckStatusEnum.SUCCESS.getNo());
        cDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        cDto.setCompanyUuid(companyUuid);
        company = companyService.selectByDto(cDto);
        if (null == company) {
            //根据域名查找商户,此处为商户不存在
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            if (loginType.equals(SystemIdEnum.AGENCY_WEB.getCode())
                    || loginType.equals(SystemIdEnum.AGENCY_h5.getCode())) {
                loginResDto.setResultMsg("您与该开发商无合作关系!");
            }else {
            	loginResDto.setResultMsg("用户不存在或已被禁用!");
            }
            return loginResDto;
        }


        if (reqDto.getLoginType().equals(SystemIdEnum.AGENCY_WEB.getCode())) {
            loginResDto = vendorWebsiteLogin(reqDto, loginResDto, company);

        } else if (reqDto.getLoginType().equals(SystemIdEnum.AGENCY_h5.getCode()) || reqDto.getLoginType().equals(SystemIdEnum.APP_AGENCY.getCode())) {
            loginResDto = vendorH5Login(reqDto, loginResDto, company);

        } else if (reqDto.getLoginType().equals(SystemIdEnum.DEVELOPERS.getCode())) {
            loginResDto = assistantWebsiteLogin(reqDto, loginResDto, company);

        } else if (reqDto.getLoginType().equals(SystemIdEnum.ASSISTANT.getCode()) || reqDto.getLoginType().equals(SystemIdEnum.APP_ASSISTANT.getCode())) {
            loginResDto = assistantH5Login(reqDto, loginResDto, company);

        } 
        // 分销小程序不会再使用
//        else if (reqDto.getLoginType().equals(SystemIdEnum.WEAPP_AGENCY.getCode())) {
//            loginResDto = vendorWeAppLogin(reqDto, loginResDto, company);
//            loginResDto.setCompanyUuid(companyUuid);
//        }

        return loginResDto;
    }

    /**
     * 分销PC登录
     *
     * @return
     */
    public LoginResDto vendorWebsiteLogin(LoginReqDto reqDto, LoginResDto loginResDto, Company company) {
        //分销登录
        List<Long> companyIds = new ArrayList<Long>();
        CompanyRelationDto relationDto = new CompanyRelationDto();
        relationDto.setDevCompany(company.getId());
        List<CompanyRelation> relationList = companyRelationService.selectListByDto(relationDto);

        for (CompanyRelation relation : relationList) {
            companyIds.add(relation.getAgentCompany());
        }

        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        PartnerInfo partnerInfo = new PartnerInfo();
        //partnerInfoDto.setHigherid(company.getId());
        partnerInfoDto.setPhone(reqDto.getPhone());
        partnerInfoDto.setStatus(MechanismStatusEnum.enable.getNo());
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        //修改查询方法 关联子表一起查询
        List<PartnerInfo> partnerList = partnerInfoService.listPartnerInfoForLogin(partnerInfoDto);
        if (null == partnerList || partnerList.size() == 0) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("尚未开通账户,请联系管理员!");
            return loginResDto;
        }
        //2.校验密码是否正确
        String password = PasswordUtil.md5Hex(reqDto.getPassword());
        partnerInfo = null;
        for (PartnerInfo info : partnerList) {
            //如果是游客身份，判断当前是否在当前开发商域名下(公司id是否是开发商[未注册公司],公司id是否是该开发商下的合作机构)
            if (PartnerInfoEnum.TOURIST_ROLE.getCode().equals(info.getUserRoleId()+"")) {
                if (!company.getId().equals(info.getHigherid()) && !companyIds.contains(info.getHigherid())) {
                    continue;
                } else {//该开发商下的游客用户
                    if (info.getPassword().equals(password)) {
                        partnerInfo = info;
                        break;
                    }
                }
            }
            //该用户绑定的中介机构不在开发商下则继续遍历下一个账户
            if (!companyIds.contains(info.getHigherid())) {
                continue;
            }
            //查到密码时，赋值给partnerInfo，进行后续操作
            if (info.getPassword().equals(password)) {
                partnerInfo = info;
                break;
            }
        }
        if (null == partnerInfo) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("密码错误");
            return loginResDto;
        }

        //验证账号是否被禁用
        String status = partnerInfo.getStatus();
        if (!"1".equals(status)) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账户冻结,请联系公司管理员!");
            return loginResDto;
        }

        //将微信号绑定至账户
        partnerInfo.setWxOpenid(reqDto.getWxOpenId());
        if (org.apache.commons.lang.StringUtils.isNotBlank(reqDto.getWxOpenId()) && !"null".equals(reqDto.getWxOpenId())) {
            PartnerInfoDto piDto = new PartnerInfoDto();
            piDto.setId(partnerInfo.getId());
            piDto.setWxOpenid(reqDto.getWxOpenId());
            rePackPartnerInfo(piDto, reqDto.getLoginType(), reqDto.getWxOpenId(), reqDto.getCompanyUuid());
            partnerInfoService.update(piDto);
        }
        
        //3.授权登陆
        Long higherId = partnerInfo.getHigherid();
        company = companyService.selectById(higherId);
        if (null != company) {
            if (PartnerInfoEnum.TOURIST_ROLE.getCode().equals(partnerInfo.getUserRoleId()+"")) {
                partnerInfo.setProvince(company.getProvince());
                partnerInfo.setCity(company.getCity());
                partnerInfo.setObjectType(company.getCompanyType());
                partnerInfo.setCompanyName(company.getCompanyName());
            }
        } else {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号对应的商户不存在!");
            return loginResDto;
        }
        
        //公司类型
        long objectType = company.getCompanyType();
        //查询对应字典值
        Dictionary dictionary = dictionaryService.selectById(objectType);
        //获取value
        String value = dictionary.getDicValue();
        if (!value.equals(CompanyTypeEnum.COMPANY_TYPE_VALUE_0.getCode())
                && !PartnerInfoEnum.TOURIST_ROLE.getCode().equals(partnerInfo.getUserRoleId()+"")) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号类型错误,请联系巧房平台管理员!");
            return loginResDto;
        }
        loginResDto.setResult("1");
        BeanUtils.copyProperties(partnerInfo, loginResDto);
        return loginResDto;
    }

    /**
     * 分销H5登录
     */
    public LoginResDto vendorH5Login(LoginReqDto reqDto, LoginResDto loginResDto, Company company) {
        return vendorWebsiteLogin(reqDto, loginResDto, company);
    }

     //  分销小程序登录，已有新版小程序
//    public LoginResDto vendorWeAppLogin(LoginReqDto reqDto, LoginResDto loginResDto, Company company) {
//        return vendorWebsiteLogin(reqDto, loginResDto, company);
//    }

    /**
     * 案场PC登录
     */
    public LoginResDto assistantWebsiteLogin(LoginReqDto reqDto, LoginResDto loginResDto, Company company) {
        PartnerInfoDto partnerInfoDto = new PartnerInfoDto();
        PartnerInfo partnerInfo = new PartnerInfo();
        partnerInfoDto.setHigherid(company.getId());
        partnerInfoDto.setPhone(reqDto.getPhone());
        partnerInfoDto.setStatus(MechanismStatusEnum.enable.getNo());
        partnerInfoDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
        //修改查询方法 关联子表一起查询
        partnerInfo = partnerInfoService.getPartnerInfoForLogin(partnerInfoDto);
        if (null == partnerInfo) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号不存在或已被禁用!");
            return loginResDto;
        }
        //游客角色不能登陆，再分销商添加用户的时候是绑定在开发商下的，做游客角色处理
        Long i = partnerInfo.getUserRoleId();
        if (i != null && PartnerInfoEnum.TOURIST_ROLE.getCode().equals(partnerInfo.getUserRoleId()+"")) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号不存在或已被禁用!");
            return loginResDto;
        }
        //获取公司类型
        long higherid = partnerInfo.getHigherid();
        company = companyService.selectById(higherid);
        if (null == company) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号对应的案场不存在!");
            return loginResDto;
        }
        //公司类型
        long objectType = company.getCompanyType();
        //查询对应字典值
        Dictionary dictionary = dictionaryService.selectById(objectType);
        //获取value
        String value = dictionary.getDicValue();
        if (!value.equals(CompanyTypeEnum.COMPANY_TYPE_VALUE_2.getCode())) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号类型错误,请联系巧房平台管理员!");
            return loginResDto;
        }
        String status = partnerInfo.getStatus();
        if (status.equals(MechanismStatusEnum.disable.getNo())) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号已被停用,请联系开发商平台管理员!");
            return loginResDto;
        }
        String password = partnerInfo.getPassword();
        if (StringUtils.isEmpty(password)) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号未设置密码!");
            return loginResDto;
        }
        String md5Password = PasswordUtil.md5Hex(reqDto.getPassword());
        if (!md5Password.equals(password)) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("密码错误!");
            return loginResDto;
        }
        if (null != company) {
            partnerInfo.setProvince(company.getProvince());
            partnerInfo.setCity(company.getCity());
            partnerInfo.setObjectType(company.getCompanyType());
            partnerInfo.setCompanyName(company.getCompanyName());
        }
        loginResDto.setResult("1");
        BeanUtils.copyProperties(partnerInfo, loginResDto);
        return loginResDto;
    }

    /**
     * 案场H5登录
     */
    public LoginResDto assistantH5Login(LoginReqDto reqDto, LoginResDto loginResDto, Company company) {
        PartnerInfoDto queryPartnerInfo = new PartnerInfoDto();

        queryPartnerInfo.setHigherid(company.getId());
        queryPartnerInfo.setPhone(reqDto.getPhone());
        queryPartnerInfo.setStatus(MechanismStatusEnum.enable.getNo());
        queryPartnerInfo.setDelFlag(DelFlagEnum.UNDEL.getNo());
        //修改查询方法 关联子表一起查询
        PartnerInfo partnerInfo = partnerInfoService.getPartnerInfoForLogin(queryPartnerInfo);
        if (null == partnerInfo) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("尚未开通账户，请联系后台管理员!");
            return loginResDto;
        }

        String status = partnerInfo.getStatus();
        if (partnerInfo.getUserRoleId() != null) {
            //防止userId为空时报错
            //游客角色不能登陆，再分销商添加用户的时候是绑定在开发商下的，做游客角色处理
            if (PartnerInfoEnum.TOURIST_ROLE.getCode().equals(partnerInfo.getUserRoleId()+"")) {
                loginResDto.setResult(ResultEnum.FAIL.getNo());
                loginResDto.setResultMsg("尚未开通账户，请联系后台管理员");
                return loginResDto;
            }
        }
        if (!"1".equals(status)) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账户冻结,请联系公司管理员!");
            return loginResDto;
        }

        //2.验证密码是否正确
        String password = PasswordUtil.md5Hex(reqDto.getPassword());
        if (!partnerInfo.getPassword().equals(password)) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("密码错误");
            return loginResDto;
        }

        //3.授权登陆
        Long higherId = partnerInfo.getHigherid();
        company = companyService.selectById(higherId);
        if (null == company) {
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号对应的商户不存在!");
            return loginResDto;
        }

        // 判断权限: 存在以下任何一种权限即可
        // 案场助手、渠道管理、楼盘分享、boss看板
        if(PartnerInfoEnum.ACCOUNT_INDIVIDUAL.getCode().equals(partnerInfo.getAccountType())){
            GetOptAuthReqDto getOptAuthReqDto = new GetOptAuthReqDto();
            getOptAuthReqDto.setUserId(String.valueOf(partnerInfo.getId()));
            getOptAuthReqDto.setRoleId(partnerInfo.getUserRoleId());
            getOptAuthReqDto.setAccountType(partnerInfo.getAccountType());
            GetOptAuthResDto getOptAuthResDto = resourcesService.getOptAuth(getOptAuthReqDto);

            if(CollectionUtils.isEmpty(getOptAuthResDto.getList())){
            	 loginResDto.setResult(ResultEnum.FAIL.getNo());
                 loginResDto.setResultMsg("您没有对应权限，请联系管理员");
                 return loginResDto;
            }
            
            if(CollectionUtils.isNotEmpty(getOptAuthResDto.getList())){
                boolean noAuth = true;
                for(String resourcesCode : getOptAuthResDto.getList()){
                    if("menu_0008".equals(resourcesCode)
                    || "menu_0010".equals(resourcesCode)
                    || "menu_0011".equals(resourcesCode)
                    || "menu_0013".equals(resourcesCode)){
                        noAuth = false;
                        break;
                    }
                }
                if(noAuth){
                    loginResDto.setResult(ResultEnum.FAIL.getNo());
                    loginResDto.setResultMsg("您没有对应权限，请联系管理员");
                    return loginResDto;
                }
            }
        }

        //将微信号绑定至账户
        partnerInfo.setWxOpenid(reqDto.getWxOpenId());
        if (!StringUtils.isEmpty(reqDto.getWxOpenId()) && !"null".equals(reqDto.getWxOpenId())) {
            PartnerInfoDto piDto = new PartnerInfoDto();
            piDto.setId(partnerInfo.getId());
            piDto.setWxOpenid(reqDto.getWxOpenId());
            rePackPartnerInfo(piDto, reqDto.getLoginType(), reqDto.getWxOpenId(), reqDto.getCompanyUuid());
            partnerInfoService.update(piDto);
        }

        partnerInfo.setProvince(company.getProvince());
        partnerInfo.setCity(company.getCity());
        partnerInfo.setObjectType(company.getCompanyType());
        partnerInfo.setCompanyName(company.getCompanyName());
        //公司类型
        if(20 != company.getCompanyType()){
            loginResDto.setResult(ResultEnum.FAIL.getNo());
            loginResDto.setResultMsg("账号类型错误,请联系巧房平台管理员!");
            return loginResDto;
        }

        //返回初始化楼盘
        String accountType = partnerInfo.getAccountType();
        CaseMemberDto cmDto = new CaseMemberDto();
        List<Long> premisesIdList = new ArrayList<>();
        if ("0".equals(accountType)) {
            //管理员,直接查询公司所有楼盘
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setCompanyId(partnerInfo.getHigherid());
            premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
            List<Premises> premisesList = premisesService.selectIdListByDto(premisesDto);
            if (null != premisesList && premisesList.size() > 0) {
                Premises premises = premisesList.get(0);
                partnerInfo.setPremisesId(String.valueOf(premises.getId()));
                partnerInfo.setPremisesName(premises.getName());
                for (Premises iteratorPremises : premisesList) {
                	premisesIdList.add(iteratorPremises.getId());
				}
            } else {
                loginResDto.setResult(ResultEnum.FAIL.getNo());
                loginResDto.setResultMsg("贵公司暂无楼盘出售,无法登录!");
                return loginResDto;
            }
        } else {
            //普通案场人员
            cmDto.setPartnerId(partnerInfo.getId());
            cmDto.setPiStatus("1");
            cmDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
            if(SystemIdEnum.ASSISTANT.getCode().equals(reqDto.getLoginType())) {
            	cmDto.setNotGroupBy("true");
            }
            List<CaseMemberDto> cmList = caseMemberService.selectParAndPreListByDto(cmDto);

            //当前登录人是否为楼盘项目总监或项目经理
            PremisesDto premisesDto = new PremisesDto();
            premisesDto.setMobileTemp(partnerInfo.getPhone());
            premisesDto.setCompanyId(partnerInfo.getHigherid());
            List<Premises> premisesList = premisesService.selectIdListByMobileTemp(premisesDto);
            if(premisesList != null && premisesList.size() > 0) {
                for (Premises premises : premisesList) {
                    CaseMemberDto cm = new CaseMemberDto();
                    cm.setPremisesId(premises.getId());
                    cm.setPremisesName(premises.getName());
                    cmList.add(cm);
                }
            }

            // 置业顾问关联的楼盘
            if(SystemIdEnum.ASSISTANT.getCode().equals(reqDto.getLoginType())){
                // 只有案场助手需要展示置业顾问报备关联的楼盘
                List<EstateAdviser> adviserList = estateAdviserService.selectListByPartner(partnerInfo.getId());
                if(CollectionUtils.isNotEmpty(adviserList)){
                    List<Long> premisesIds = adviserList.stream().map(EstateAdviser::getPremisesId).collect(Collectors.toList());
                    premisesDto = new PremisesDto();
                    premisesDto.setPremisesIds(premisesIds);
                    premisesDto.setPremisesStatus(PremisesStatusEnum.type1.getNo());
                    List<Premises> adviserPremisesList = premisesService.selectIdListByDto(premisesDto);
                    if(CollectionUtils.isNotEmpty(adviserPremisesList)) {
                        for (Premises premises : adviserPremisesList) {
                            CaseMemberDto cm = new CaseMemberDto();
                            cm.setPremisesId(premises.getId());
                            cm.setPremisesName(premises.getName());
                            cmList.add(cm);
                        }
                    }
                }
            }

            if (null != cmList && cmList.size() > 0) {
                CaseMemberDto returnCmDto = cmList.get(0);
                partnerInfo.setPremisesId(String.valueOf(returnCmDto.getPremisesId()));
                partnerInfo.setPremisesName(returnCmDto.getPremisesName());
                for (CaseMemberDto caseMember : cmList) {
                	premisesIdList.add(caseMember.getPremisesId());
				}
            } else {
                loginResDto.setResult(ResultEnum.FAIL.getNo());
                loginResDto.setResultMsg("您还未驻守任何项目,无法登录!");
                return loginResDto;
            }
        }
        partnerInfo.setPremisesIds(premisesIdList);
        loginResDto.setResult("1");
        BeanUtils.copyProperties(partnerInfo, loginResDto);
        return loginResDto;
    }

	public String getDomainName() {
		return domainName;
	}
	
	/**
	 * 重新组装partner信息。在案场H5，分销H5登录的时候需要填充进去最后一次登录渠道信息以及对应的wxopenId
	 * @param pi
	 * @param loginType
	 * @param openId
	 */
	private void rePackPartnerInfo(PartnerInfoDto pi, String loginType, String openId, String companyUuid) {
		pi.setLastLoginSystemId(loginType);
		String accessToken = wxAccessTokenCacheUtils.getAccessTokenBySystemId(companyUuid, loginType, "");
		if(accessToken != null && !StringUtils.isEmpty(accessToken)) {
			String unionId = wxReqestUtil.getUnionId(openId, companyUuid, loginType, 0);
			if(unionId != null) {
				String appId = weixinCommon.getRealAppId(loginType, companyUuid);
				WxBindDto wxBindDto = new WxBindDto();
				wxBindDto.setUnionId(unionId);
				wxBindDto.setAppId(appId);
				wxBindDto.setWxOpenId(openId);
				wxBindDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				WxBind wxBind = wxBindMapper.selectByDto(wxBindDto);
				if(wxBind != null) {
					pi.setWeappOpenid(wxBind.getWeappOpenId());
				}
			}
		}
	}
	
	/**
	 * 登出
	 * 分销小程序登出的入口不在这，所以不在此添加分销小程序的判断
	 * @param loginReqDto
	 */
	@Override
	public void loginOut(LoginOutReqDto loginReqDto) {
		if(clearFlag(loginReqDto.getLoginType(), loginReqDto.getCompanyUuid())) {
			// 根据ID清空，注意sql中需要添加额外判断，当systemID为7的时候。（为了兼容历史数据，分销小程序开关可能没有打开）
			String userId = loginReqDto.getUserId();
			if(!StringUtils.isEmpty(userId)) {
				partnerInfoService.clearOpenidByUserId(Long.parseLong(userId));
			}
		}
	}
	
	// 清除分销的时候需要判断当前人员的enableweappmsg字段(未开启，则不能清除，还发至原公众号)
	private static final String[] OPENID_CLEAR_SYSTEMID = new String[] {SystemIdEnum.AGENCY_h5.getCode(), 
			SystemIdEnum.ASSISTANT.getCode()};
		
	/**
	 * 判断渠道是否要进行清除wxopenId
	 * @param systemId
	 * @return
	 */
	private boolean clearFlag(String systemId, String companyUuid) {
		if(!systemClearFlag(systemId, companyUuid)) {
			return false;
		}
		return true;
	}
	
	/**
	 * 判断是否符合渠道清理的标准
	 * @param systemId
	 * @return
	 */
	private boolean systemClearFlag(String systemId, String companyUuid) {
		for(int i = 0;  i < OPENID_CLEAR_SYSTEMID.length; i ++) {
			if(OPENID_CLEAR_SYSTEMID[i].equals(systemId)) {
				return true;
			}
		}
		return false;
	}
	
}
